from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import jwt
import time
from user.models import User
from user.auth import login_verify
from wechatpy import parse_message, create_reply
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.utils import check_signature
from wechatpy.oauth import WeChatOAuth
from user.wx_api import get_user_info, create_qrcode, APPID, APPSECRET
from user.redis_tools import RedisCache
import uuid
from user.config import BASE_URL, TOKEN, AUTH_REDIS_KEY_PREFIX, EXPIRE_SECONDS

r = RedisCache()


def login(request):
    return render(request, "login.html")


def auth(request):
    return render(request, "auth.html")


@csrf_exempt
def wechat(request):
    # GET 方式用于微信公众平台绑定验证
    if request.method == 'GET':
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        echo_str = request.GET.get('echostr', '')
        try:
            check_signature(TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            echo_str = '错误的请求'
        response = HttpResponse(echo_str)
        return response

    elif request.method == 'POST':
        msg = parse_message(request.body)
        if msg.type == 'event':
            if "login" in str(msg):
                user_info = get_user_info(msg.source)
                reply = create_reply('你好，{}！欢迎登陆报告平台。'.format(user_info['nickname']), msg)
                response = HttpResponse(reply.render(), content_type="application/xml")

                scene_id = msg.scene_id
                key = AUTH_REDIS_KEY_PREFIX + scene_id
                r.set(key, user_info["openid"], ex=EXPIRE_SECONDS)

                return response


def get_qrcode(request):
    scene_id = "login_" + str(uuid.uuid4())
    form_data = {
        "expire_seconds": EXPIRE_SECONDS,
        "action_name": "QR_STR_SCENE",
        "action_info": {
            "scene": {"scene_str": scene_id}
        }
    }
    key = AUTH_REDIS_KEY_PREFIX + scene_id
    r.set(key, "", ex=EXPIRE_SECONDS)
    qr_code = create_qrcode(form_data)
    return JsonResponse({"qr_code": qr_code, "scene_id": scene_id, "expires": int(time.time()) + EXPIRE_SECONDS})


def get_jwt_token(openid):
    payload = {
        "openid": openid,
        "iat": int(time.time()),
        "exp": int(time.time()) + 60 * 60,
    }
    return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')


def parse_jwt_token(token):
    return jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])


def jwt_verify(request):
    wechat_oauth = WeChatOAuth(APPID, APPSECRET, BASE_URL + "user/auth/", scope="snsapi_userinfo")
    code = request.GET.get("code", "")
    if code:
        wechat_oauth.fetch_access_token(code)
        user_info = wechat_oauth.get_user_info()
        openid = user_info["openid"]
        print("---------------------wp_login---------------------", openid)
        return jwt_verify_result(openid)

    scene_id = request.GET.get("scene_id", "")
    if scene_id:
        key = AUTH_REDIS_KEY_PREFIX + scene_id
        openid = r.get(key)["result"]
        if openid:
            return jwt_verify_result(openid)
        return JsonResponse({"status": "error", "msg": "no_open_id"})
    return JsonResponse({"status": "error", "msg": "no scene_id"})


def jwt_verify_result(openid):
    user_info = get_user_info(openid)
    try:
        print("---------------------login---------------------")
        user = User.objects.get(openid=openid)
        print("---------------------login---------------------", user)
    except:
        print("---------------------register---------------------")
        user = User.objects.create(
            openid=user_info['openid'], nickname=user_info['nickname'], sex=user_info['sex'],
            language=user_info['language'], city=user_info['city'], province=user_info['province'],
            country=user_info['country'], avatar=user_info['headimgurl']
        )
        user.save()
    token = get_jwt_token(user_info['openid'])
    return JsonResponse({"status": "success", "user": user_info, "token": str(token, encoding="utf-8")})


def get_authorize_url(request):
    wechat_oauth = WeChatOAuth(APPID, APPSECRET, BASE_URL + "user/auth/", scope="snsapi_userinfo")
    return JsonResponse({"authorize_url": wechat_oauth.authorize_url})


@login_verify
def isLogin(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    auth_item = parse_jwt_token(token)
    user = User.objects.get(openid=auth_item["openid"])
    user_info = {
        "nickname": user.nickname,
        "avatar": user.avatar
    }
    return JsonResponse({'status': 'success', "msg": "已登录", "user_info": user_info})
